package com.sangeng.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sangeng.domain.ResponseResult;
import com.sangeng.dto.UserDto;
import com.sangeng.entity.Role;
import com.sangeng.entity.RoleMenu;
import com.sangeng.entity.User;
import com.sangeng.entity.UserRole;
import com.sangeng.service.IRoleService;
import com.sangeng.service.IUserRoleService;
import com.sangeng.service.IUserService;
import com.sangeng.utils.BeanCopyUtils;
import com.sangeng.vo.LinkVo;
import com.sangeng.vo.PageVo;
import com.sangeng.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/system/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IRoleService roleService;

    @RequestMapping("/list")
    public ResponseResult list(String userName, String phonenumber, String status, int pageNum, int pageSize)
    {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(userName), User::getUserName, userName);
        wrapper.like(StringUtils.hasText(phonenumber), User::getPhonenumber, phonenumber);
        wrapper.eq(StringUtils.hasText(status), User::getStatus, status);

        Page<User> page = new Page<>(pageNum, pageSize);
        Page<User> page1 = userService.page(page, wrapper);

        List<User> roles = page1.getRecords();

        PageVo pageVo = new PageVo(roles, page1.getTotal());

        return ResponseResult.okResult(pageVo);

    }

    // 新增用户
    @RequestMapping
    public ResponseResult addUser(@RequestBody UserVo userVO)
    {
        // 用 BeanCopyUtils将userVO转换为User
        User user = BeanCopyUtils.copyBean(userVO, User.class);
        userService.save(user);
        // 根据roleIds 先删除之前用户角色关联 再添加
        userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getId()));
        Arrays.stream(userVO.getRoleIds()).forEach(roleId -> {
            userRoleService.save(new UserRole(user.getId(), roleId));
        });
        return ResponseResult.okResult();
    }

    // 更新用户信息接口
    @PutMapping
    public ResponseResult updateUser(@RequestBody UserDto userDto)
    {

        /// 更新user
        User user = userService.getById(userDto.getId());
        user.setEmail(userDto.getEmail());
        user.setNickName(userDto.getSex());
        user.setStatus(userDto.getStatus());
        user.setNickName(userDto.getNickName());
        user.setPhonenumber(userDto.getPhonenumber());
        userService.saveOrUpdate(user);


        /// 更新user_role表
        userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userDto.getId()));
        Arrays.stream(userDto.getRoleIds()).forEach(roleId -> {
            userRoleService.save(new UserRole(userDto.getId(), roleId));
        });
        return ResponseResult.okResult();
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public ResponseResult deleteUser(@PathVariable("id") Long id)
    {
        userService.removeById(id);
        return ResponseResult.okResult();
    }

    // 获取用户详情
    @GetMapping("/{id}")
    public ResponseResult getUser(@PathVariable("id") Long id)
    {
        Map map = new HashMap();

        /// 1.获取所有角色id
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId, id);
        List<UserRole> list = userRoleService.list(wrapper);
        // 获取角色Ids的集合
        List<Long> roleIds = list.stream().map(UserRole::getRoleId).collect(Collectors.toList());
         map.put("roleIds", roleIds);

        /// 2.  获取所有角色
        map.put("roles", roleService.list());

        /// 3. 获取用户信息
        map.put("user", userService.getById(id));
        return ResponseResult.okResult(map);
    }
}
